from rest_framework import serializers
from apps.api.function.models import FunctionModel
from apps.api.project.models import ProjectModel
from utils.common import date_format


class FunctionModelSerializer(serializers.ModelSerializer):
    project = serializers.StringRelatedField(label="所属项目名称", help_text="所属项目名称")
    project_id = serializers.PrimaryKeyRelatedField(queryset=ProjectModel.objects.all(), label="所属项目ID",
                                                    help_text="所属项目ID")

    class Meta:
        model = FunctionModel
        exclude = ["is_delete", "update_time"]
        extra_kwargs = {
            "create_time": {
                "read_only": True,
                "format": date_format()
            }
        }

    def create(self, validated_data):
        project = validated_data.pop("project_id")
        validated_data["project_id"] = project.id
        return super().create(validated_data)

    def update(self, instance, validated_data):
        project = validated_data.pop("project_id")
        validated_data["project_id"] = project.id
        return super().update(instance, validated_data)
